package com.wetao.module_homework;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.Target;
import com.daquexian.flexiblerichtextview.FlexibleRichTextView;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.response.ExplainBean;
import com.wetao.lib_common.bean.response.QueryExamQuestionsResponse;
import com.wetao.lib_common.bean.response.StudentExamQuestion;
import com.wetao.lib_common.bean.vo.ValueBean;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.service.PlayService;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.FormulaUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MyDividerItemDecoration;
import com.wetao.lib_common.utils.OptionStr;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.WrapContentLinearLayoutManager;
import com.wetao.lib_common.view.CustomPopWindow;
import com.wetao.module_homework.adapter.HomeworkDetailNumAdapter;
import com.wetao.module_homework.adapter.HomeworkExplainAdapter;
import com.wetao.module_homework.contract.HomeworkDetailActivityCon;
import com.wetao.module_homework.presenter.HomeworkDetailActivityPre;

import org.scilab.forge.jlatexmath.core.AjLatexMath;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.github.kbiakov.codeview.classifier.CodeProcessor;

@Route(path = ConstantArouter.PATH_HOMEWORK_DETAILACTIVITY)
public class HomeworkDetailActivity extends BaseActivity<HomeworkDetailActivityCon.View, HomeworkDetailActivityPre>
        implements HomeworkDetailActivityCon.View {


    @Autowired
    String examName;
    @Autowired
    int examId;
    @Autowired
    int publishId;
    @Autowired
    int studentExamId;

    @BindView(R2.id.tv_title)
    TextView tv_title;
    private QueryExamQuestionsResponse mExam;
    @BindView(R2.id.rv_num)
    RecyclerView rv_num;
    private HomeworkDetailNumAdapter mHomeworkDetailNumAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private MyDividerItemDecoration mDividerItemDecoration;


    @BindView(R2.id.btn_next_question)
    Button btn_next_question;
    @BindView(R2.id.ibtn_h_prev)
    ImageButton ibtn_h_prev;
    @BindView(R2.id.ibtn_h_next)
    ImageButton ibtn_h_next;
    private boolean mIsLastQuestion;
    private int mMaxCountLine = 0; //一行最多放多少个
    private int mNumfirstVisible;
    private int mNumfirstComplete;
    private int mNumlastVisible;
    private int mNumlastComplete;
    private int mQuestionIndex;

    @BindView(R2.id.ll_screen)
    LinearLayout ll_screen;
    @BindView(R2.id.tv_screen_0)
    TextView tv_screen_0;
    @BindView(R2.id.tv_screen_1)
    TextView tv_screen_1;
    @BindView(R2.id.ll_other)
    LinearLayout ll_other;
    private boolean mIsHasScreen = false;
    private boolean mIsShowScreen = false;

    @BindView(R2.id.ll_media)
    LinearLayout ll_media;
    @BindView(R2.id.ll_pop_teacher)
    LinearLayout ll_pop_teacher;
    @BindView(R2.id.iv_popDowUp_teacher)
    ImageView iv_popDownUp;
    @BindView(R2.id.tv_pop_teacher_name)
    TextView tv_pop_teacher_name;
    @BindView(R2.id.ll_understand)
    LinearLayout ll_understand;
    @BindView(R2.id.iv_understand)
    ImageView iv_understand;
    @BindView(R2.id.tv_understand)
    TextView tv_understand;
    @BindView(R2.id.ll_no_understand)
    LinearLayout ll_no_understand;
    @BindView(R2.id.iv_no_understand)
    ImageView iv_no_understand;
    @BindView(R2.id.tv_no_understand)
    TextView tv_no_understand;
    @BindView(R2.id.ll_video)
    LinearLayout ll_video;
    @BindView(R2.id.tv_video)
    TextView tv_video;
    @BindView(R2.id.ll_audio)
    LinearLayout ll_audio;
    @BindView(R2.id.iv_audio_play_or_pause)
    ImageView iv_audio_play_or_pause;
    @BindView(R2.id.tv_audio_time)
    TextView tv_audio_time;
    @BindView(R2.id.rsb_audio_progress)
    RangeSeekBar rsb_audio_progress;
    @BindView(R2.id.iv_voice_play_or_pause)
    ImageView iv_voice_play_or_pause;
    //讲解弹框
    private RecyclerView rcy_pop_teacher;
    private HomeworkExplainAdapter explainTeacherAdapter;
    //老师讲解集合
    private List<ExplainBean> explainListBeans = new ArrayList<>();
    private ExplainBean curExplainBean; //当前的讲解老师
    private CustomPopWindow popWindowTeacher;
    private PlayService playService;
    private PlayService.PlayBinder playBinder;
    private AudioManager audioManager;
    private String audioPath;
    //最大音量
    int maxVolume;
    //当前音量
    int currentVolume;
    private float rsb_fromUser_value = 0;  //拖动位置值
    private int mDuration;  // 音频总时长
    private boolean isPlayVoiceComment = false;
    private boolean isCommentAutoPaly = false;
    @BindView(R2.id.ll_comment)
    LinearLayout ll_comment;
    @BindView(R2.id.tv_no_comment)
    TextView tv_no_comment;
    @BindView(R2.id.iv_comment_play_or_pause)
    ImageView iv_comment_play_or_pause;
    @BindView(R2.id.tv_comment_time)
    TextView tv_comment_time;
    @BindView(R2.id.rsb_comment_progress)
    RangeSeekBar rsb_comment_progress;
    @BindView(R2.id.iv_comment_voice)
    ImageView iv_comment_voice;


    @BindView(R2.id.tv_my_answer)
    TextView tv_my_answer;
    @BindView(R2.id.ll_my_answer)
    LinearLayout ll_my_answer;
    @BindView(R2.id.iv_my_answer_0)
    ImageView iv_my_answer_0;
    @BindView(R2.id.iv_my_answer_1)
    ImageView iv_my_answer_1;
    @BindView(R2.id.iv_my_answer_2)
    ImageView iv_my_answer_2;
    @BindView(R2.id.frtv_explain)
    FlexibleRichTextView frtv_explain;
    @BindView(R2.id.frtv_answer)
    FlexibleRichTextView frtv_answer;
    @BindView(R2.id.tv_reViewResult)
    TextView tv_reViewResult;
    @BindView(R2.id.tv_no_explain)
    TextView tv_no_explain;
    @BindView(R2.id.tv_no_my_answer)
    TextView tv_no_my_answer;



    @BindView(R2.id.frtv_exam_content)
    FlexibleRichTextView frtv;

    private boolean mIsInited = false;

    @Override
    public int getLayoutId() {
        return R.layout.homework_detail_activity;
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }

    @Override
    public HomeworkDetailActivityPre createPresenter() {
        return new HomeworkDetailActivityPre(this);
    }

    @Override
    public HomeworkDetailActivityCon.View createView() {
        return this;
    }

    @Override
    public void init() {

        ////CodeProcessor.init(this);
        ////AjLatexMath.init(this); //

        tv_title.setText(examName == null ? "" : StringUtil.replaceAmp(examName));
        initRecyclerView();
        createTeacherPop();
        initPlayService();
        initVolume();
        listenerRangeChanged();
        LogUtils.i("examName: " + examName + ", examId: " + examId + ", publishId: " + publishId + ", studentExamId: " + studentExamId);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(playBinder != null) {
            playBinder.callPauseMusic();
        }
    }

    @Override
    protected void onDestroy() {
        if(playConnection != null) {
            unbindService(playConnection);
            playConnection = null;
        }

        super.onDestroy();
        if(playBinder != null) {
            playBinder = null;
        }
        if(playService != null) {
            playService.setCallback(null);
            playService = null;
        }
    }

    @Override
    public void getQuestionListResult(BaseResponse<QueryExamQuestionsResponse> response) {
        if(response.getData() != null) {
            mExam = response.getData();
            mHomeworkDetailNumAdapter.updateData(mExam.getQuestionList());
            setmQuestionIndex(0);
            mIsInited = true;
        }
    }

    @Override
    public void getQuestionListFailed() {

    }

    @Override
    public void updateUnderstandResult(BaseResponse resp) {
    }

    @Override
    public void updateUnderstandFail() {

    }

    @OnClick({R2.id.iv_back,
            R2.id.btn_next_question,
            R2.id.ibtn_h_prev,
            R2.id.ibtn_h_next,
            R2.id.tv_screen_0,
            R2.id.tv_screen_1,
            R2.id.ll_pop_teacher,
            R2.id.ll_understand,
            R2.id.ll_no_understand,
            R2.id.ll_video,
            R2.id.iv_audio_play_or_pause,
            R2.id.iv_voice_play_or_pause,
            R2.id.iv_comment_play_or_pause,
            R2.id.iv_comment_voice,
    })
    public void onClickView(View v) {
        int id = v.getId();
        if(id == R.id.iv_back) {
            finish();
        }
        if(!mIsInited) {
            return;
        }
        if(id == R.id.btn_next_question) {
            //mTouchGestureListener.setDoodleTranslationXY(-200f, -300f);
            if(playBinder != null && playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                playBinder.callPauseMusic();
            }
            if(mIsLastQuestion) {
                //完成
                finish();
            } else {
                //下一题

                int temp = mQuestionIndex + 1;
                setmQuestionIndex(temp);
                mHomeworkDetailNumAdapter.setmCurPosition(temp);
                if(temp >= 0) {
                    if(temp < mNumfirstComplete) {
                        prevLine();
                    } else if(temp > mNumlastComplete) {
                        nextLine();
                    }
                }
            }
        } else if(id == R.id.ibtn_h_prev) {
            prevLine();
        } else if(id == R.id.ibtn_h_next) {
            nextLine();
        } else if(id == R.id.tv_screen_0) {
            if(!mIsShowScreen) {
                mIsShowScreen = true;
                switchScreen();
            }
        } else if(id == R.id.tv_screen_1) {
            if(mIsShowScreen) {
                mIsShowScreen = false;
                switchScreen();
            }
        } else if(id == R.id.ll_pop_teacher) {
            showExplainPop();
        }else if (id == R.id.ll_understand) {
            ll_no_understand.setSelected(false);
            iv_no_understand.setSelected(false);
            ll_understand.setSelected(true);
            iv_understand.setSelected(true);
            mExam.getQuestionList().get(mQuestionIndex).setIsUndrestand(1);
            updateUnderStandReq(mExam.getQuestionList().get(mQuestionIndex).getAnswerId(), 1);
        } else if (id == R.id.ll_no_understand) {
            ll_no_understand.setSelected(true);
            iv_no_understand.setSelected(true);
            ll_understand.setSelected(false);
            iv_understand.setSelected(false);
            mExam.getQuestionList().get(mQuestionIndex).setIsUndrestand(0);
            updateUnderStandReq(mExam.getQuestionList().get(mQuestionIndex).getAnswerId(), 0);
        }else if (id == R.id.ll_video) {
            if(playBinder != null) {
                playBinder.callPauseMusic();
            }
            gotoPlayVideActivity();
        } else if (id == R.id.iv_audio_play_or_pause) {
            isPlayVoiceComment = false;
            audioPlayOrPause();
            resetTime(false, true);
        } else if (id == R.id.iv_voice_play_or_pause || id == R.id.iv_comment_voice) {

            if (currentVolume > 0) {
                currentVolume = 0;
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
            } else {
                currentVolume = maxVolume / 2;
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
            }
            if (iv_voice_play_or_pause.isSelected()){
                iv_voice_play_or_pause.setSelected(false);
                iv_voice_play_or_pause.setImageResource(R.drawable.common_voice);


                iv_comment_voice.setSelected(false);
                iv_comment_voice.setImageResource(R.drawable.common_voice);

            }else{
                iv_voice_play_or_pause.setSelected(true);
                iv_voice_play_or_pause.setImageResource(R.drawable.common_voice_close);

                iv_comment_voice.setSelected(true);
                iv_comment_voice.setImageResource(R.drawable.common_voice_close);
            }
        } else if(id == R.id.iv_comment_play_or_pause) {
            isPlayVoiceComment = true;
            audioPlayOrPause();
            resetTime(true, false);
        }
    }

    private void prevLine() {
        if(mNumfirstComplete - mMaxCountLine >= 0) {
            rv_num.scrollToPosition(mNumfirstComplete - mMaxCountLine);
        } else {
            rv_num.scrollToPosition(0);
        }
    }

    private void nextLine() {
        if(mNumlastComplete + mMaxCountLine >= mHomeworkDetailNumAdapter.getItemCount()) {
            rv_num.scrollToPosition(mHomeworkDetailNumAdapter.getItemCount() - 1);
        } else {
            rv_num.scrollToPosition(mNumlastComplete + mMaxCountLine);
        }
    }

    private void initRecyclerView() {
        mLayoutManager = new WrapContentLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mHomeworkDetailNumAdapter = new HomeworkDetailNumAdapter();
        rv_num.setLayoutManager(mLayoutManager);
        mDividerItemDecoration = new MyDividerItemDecoration(this, LinearLayoutManager.HORIZONTAL, R.drawable.divider_mileage_voice_class);
        //rv_num.addItemDecoration(mDividerItemDecoration);
        rv_num.setItemAnimator( new DefaultItemAnimator());
        rv_num.setAdapter(mHomeworkDetailNumAdapter);
        ((HomeworkDetailNumAdapter)mHomeworkDetailNumAdapter).setOnItemClickListener(new HomeworkDetailNumAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LogUtils.i("onItemClick--" + position);
                if(playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                    playBinder.callPauseMusic();
                }
                setmQuestionIndex(position);
            }

            @Override
            public void onPositionChange(int position) {

            }

            @Override
            public void onIsLastQuestion(boolean isLastQuestion) {
                mIsLastQuestion = isLastQuestion;
                if(mIsLastQuestion) {
                    btn_next_question.setText("完成");
                } else {
                    btn_next_question.setText("下一题");
                }
            }
        });
        rv_num.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                LogUtils.i("m1: onScrolled dx = " + dx + ", dy = " + dy);

                LinearLayoutManager layoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
                if(layoutManager != null) {
                    mNumfirstVisible  = layoutManager.findFirstVisibleItemPosition();
                    mNumfirstComplete = layoutManager.findFirstCompletelyVisibleItemPosition();
                    mNumlastVisible  = layoutManager.findLastVisibleItemPosition();
                    mNumlastComplete = layoutManager.findLastCompletelyVisibleItemPosition();
                    LogUtils.i("m1: onScrolled -- FirstVisible = " + mNumfirstVisible + ", FirstComplete = " + mNumfirstComplete +", LastVisible = " +  mNumlastVisible +", LastComplete = " +  mNumlastComplete);
                    //HomeworkNumAdapter.NumHolder numHolder = (HomeworkNumAdapter.NumHolder)rv_num.findViewHolderForAdapterPosition(firstVisible);
                    if(mNumlastComplete - mNumfirstComplete > mMaxCountLine) {
                        mMaxCountLine = mNumlastComplete - mNumfirstComplete;
                    }
                    if(mNumfirstComplete == 0) {
                        ibtn_h_prev.setImageResource(R.drawable.common_rc_left_s);
                        ibtn_h_prev.setClickable(false);
                    } else {
                        ibtn_h_prev.setImageResource(R.drawable.common_rc_left_n);
                        ibtn_h_prev.setClickable(true);
                    }

                    if(mNumlastComplete == mHomeworkDetailNumAdapter.getItemCount() - 1) {
                        ibtn_h_next.setImageResource(R.drawable.common_rc_right_s);
                        ibtn_h_next.setClickable(false);
                    } else {
                        ibtn_h_next.setImageResource(R.drawable.common_rc_right_n);
                        ibtn_h_next.setClickable(true);
                    }
                }
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void setmQuestionIndex(int index) {
        mQuestionIndex = index;

        if(mExam == null || mExam.getQuestionList() == null) {
            LogUtils.e("mExam == null || mExam.getQuestionList() == null");
            return;
        }

        playBinder.callStopMusic();
        isCommentAutoPaly = false;
        if(!StringUtil.isEmpty(mExam.getQuestionList().get(mQuestionIndex).getVoiceComment())) {
            isPlayVoiceComment = true;
            setPlayMusicUrl(mExam.getQuestionList().get(mQuestionIndex).getVoiceComment());
        }
        if(mExam.getQuestionList().get(mQuestionIndex).getScreenId() != null) {
            mIsHasScreen = true;
            if(mQuestionIndex == 0) {
                mIsShowScreen = true;
            } else {
                if(mExam.getQuestionList().get(mQuestionIndex - 1).getScreenId() != null
                && mExam.getQuestionList().get(mQuestionIndex - 1).getScreenId().intValue() != mExam.getQuestionList().get(mQuestionIndex).getScreenId().intValue()) {
                    mIsShowScreen = true;
                } else {
                    mIsShowScreen = false;
                }
            }
        } else {
            mIsHasScreen = false;
            mIsShowScreen = false;
        }

        switchScreen();
        showOther();
    }

    /**
     * 试题讲解已懂未懂请求
     * @return
     */
    private void updateUnderStandReq(Integer id, Integer isUnderstand) {
        getPresenter().updateUnderstand(ComUtil.getHashmapByStr(new String[]{"id","isUndrestand"},new String[]{String.valueOf(id), String.valueOf(isUnderstand)}), false, false);
    }

    private void switchScreen() {
        if(mIsHasScreen) {
            ll_screen.setVisibility(View.VISIBLE);
            if(mIsShowScreen) {
                tv_screen_0.setBackgroundResource(R.drawable.shape_line_on_right_d);
                tv_screen_0.setTextColor(Color.parseColor("#ffffff"));
                tv_screen_1.setBackgroundResource(R.drawable.shape_line_on_left);
                tv_screen_1.setTextColor(Color.parseColor("#333333"));
                ll_other.setVisibility(View.GONE);
                showFlexibleRichTextView(frtv, mExam.getQuestionList().get(mQuestionIndex).getQuestionScreen()
                        , null
                        , null);
            } else {
                tv_screen_0.setBackgroundResource(R.drawable.shape_line_on_right);
                tv_screen_0.setTextColor(Color.parseColor("#333333"));
                tv_screen_1.setBackgroundResource(R.drawable.shape_line_on_left_d);
                tv_screen_1.setTextColor(Color.parseColor("#ffffff"));
                ll_other.setVisibility(View.VISIBLE);
                showFlexibleRichTextView(frtv, mExam.getQuestionList().get(mQuestionIndex).getQuestion()
                        , mExam.getQuestionList().get(mQuestionIndex).getOptions()
                        , mExam.getQuestionList().get(mQuestionIndex).getQuestionNo().intValue() + "");
            }
        } else {
            ll_screen.setVisibility(View.GONE);
            ll_other.setVisibility(View.VISIBLE);

            showFlexibleRichTextView(frtv, mExam.getQuestionList().get(mQuestionIndex).getQuestion()
                    , mExam.getQuestionList().get(mQuestionIndex).getOptions()
                    , mExam.getQuestionList().get(mQuestionIndex).getQuestionNo().intValue() + "");
        }
    }

    private void showOther() {
        curExplainBean = null;
        StudentExamQuestion question = mExam.getQuestionList().get(mQuestionIndex);

        explainListBeans.clear();
        if (question.getExplainList()!=null){
            explainListBeans.addAll(question.getExplainList());
        }
        explainTeacherAdapter.setData(explainListBeans);
        if (explainListBeans.size()>0){
            ll_pop_teacher.setVisibility(View.VISIBLE);
            ll_media.setVisibility(View.VISIBLE);
            initExplainView(curExplainBean = explainListBeans.get(0));
        }else {
            //没有试题详解不显示
            ll_pop_teacher.setVisibility(View.GONE);
            ll_media.setVisibility(View.GONE);
            ll_video.setVisibility(View.GONE);
            ll_audio.setVisibility(View.GONE);
        }

        if(question.getIsUndrestand() != null
                && question.getIsUndrestand().intValue() == 0) {
            ll_no_understand.setSelected(true);
            iv_no_understand.setSelected(true);
            ll_understand.setSelected(false);
            iv_understand.setSelected(false);
        }else if(question.getIsUndrestand() != null
                && question.getIsUndrestand().intValue() == 1) {
            ll_no_understand.setSelected(false);
            iv_no_understand.setSelected(false);
            ll_understand.setSelected(true);
            iv_understand.setSelected(true);
        }else {
            ll_no_understand.setSelected(false);
            iv_no_understand.setSelected(false);
            ll_understand.setSelected(false);
            iv_understand.setSelected(false);
        }


        tv_my_answer.setVisibility(View.GONE);
        ll_my_answer.setVisibility(View.GONE);
        tv_no_my_answer.setVisibility(View.GONE);
        if(!StringUtil.isEmpty(question.getDoodle())) {
            ll_my_answer.setVisibility(View.VISIBLE);
            List<String> list = StringUtil.strToList(question.getDoodle(), ",");
            set_iv_my_answer(list);
        } else if(question.getAnswerType() != null && question.getAnswerType().intValue() == 2) {
            if(StringUtil.isEmpty(question.getAnswerContent())) {
                tv_no_my_answer.setVisibility(View.VISIBLE);
                tv_no_my_answer.setText("暂无作答");
            } else {
                ll_my_answer.setVisibility(View.VISIBLE);
                List<String> list = StringUtil.strToList(question.getAnswerContent(), ",");
                set_iv_my_answer(list);
            }

        } else {

            if(StringUtil.isEmpty(question.getAnswerContent())) {
                tv_no_my_answer.setVisibility(View.VISIBLE);
                tv_no_my_answer.setText("暂无作答");
            } else {
                tv_my_answer.setVisibility(View.VISIBLE);
                tv_my_answer.setText(question.getAnswerContent());
            }
        }

        StringBuilder explainStringBuilder = new StringBuilder();
        if(!StringUtil.isEmpty(question.getExplain())) {
            explainStringBuilder.append(FormulaUtil.reLatex(question.getExplain()));
            LogUtils.i(explainStringBuilder.toString());
            frtv_explain.resetTextView();
            frtv_explain.setText(explainStringBuilder.toString());
            tv_no_explain.setVisibility(View.GONE);
            frtv_explain.setVisibility(View.VISIBLE);
        } else {
            explainStringBuilder.append("暂无试题解析");
            frtv_explain.resetTextView();
            frtv_explain.setText(explainStringBuilder.toString());
            tv_no_explain.setVisibility(View.VISIBLE);
            frtv_explain.setVisibility(View.GONE);
        }


        frtv_answer.resetTextView();
        StringBuilder answerStringBuilder = new StringBuilder();
        if(question.getAnswers() != null && question.getAnswers().size() > 0) {
            for(String str : question.getAnswers()) {
                if(str.startsWith("{\"value\":") && JsonUtils.isGoodJson(str)) {
                    try {
                        ValueBean valueBean = JsonUtils.fromJson(str, ValueBean.class);
                        answerStringBuilder.append(FormulaUtil.reLatex(valueBean.getValue()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    answerStringBuilder.append(FormulaUtil.reLatex(str));
                }
            }
            LogUtils.i(answerStringBuilder.toString());
            frtv_answer.setText(answerStringBuilder.toString());
        } else {
            answerStringBuilder.append("暂无标准答案");
            frtv_answer.setText(answerStringBuilder.toString());
        }

        if(StringUtil.isEmpty(question.getVoiceComment())) {
            ll_comment.setVisibility(View.GONE);
            tv_no_comment.setVisibility(View.VISIBLE);
        } else{
            ll_comment.setVisibility(View.VISIBLE);
            tv_no_comment.setVisibility(View.GONE);
        }

        resetTime(true, true);

        if(mExam.getOngoing() != null && mExam.getOngoing().intValue() == 1) {
            tv_reViewResult.setText("正在智能批阅中~");
        } else {
            String str = "我的得分：";
            if(question.getMyScore() == null) {
                str += "暂未批阅";
            } else {
                float score = question.getMyScore().floatValue();
                if((score * 10) % 5 == 5) {
                    str = str + ((int)score + 0.5);
                } else {
                    str = str + (int)score;
                }
                str += "分";
            }
            str += "          本题满分：";
            if(question.getQuestionScore() == null) {
                str += "无";
            } else {
                float score = question.getQuestionScore().floatValue();
                if((score * 10) % 5 == 5) {
                    str = str + ((int)score + 0.5);
                } else {
                    str = str + (int)score;
                }
                str += "分";
            }
            tv_reViewResult.setText(str);
        }
    }

    private void set_iv_my_answer(List<String> list) {
        iv_my_answer_0.setVisibility(View.GONE);
        iv_my_answer_1.setVisibility(View.GONE);
        iv_my_answer_2.setVisibility(View.GONE);

        if(null == list) return;
        
        if(list.size() == 1) {
            iv_my_answer_0.setVisibility(View.VISIBLE);
            LogUtils.i("我的答案图片：" + list.get(0));
            Glide.with(this).asBitmap()
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .load(list.get(0)).into(iv_my_answer_0);
        } else if(list.size() == 2) {
            iv_my_answer_0.setVisibility(View.VISIBLE);
            iv_my_answer_1.setVisibility(View.VISIBLE);
            Glide.with(this).asBitmap()
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .load(list.get(0)).into(iv_my_answer_0);
            Glide.with(this).asBitmap()
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .load(list.get(1)).into(iv_my_answer_1);
        } else if(list.size() >= 3) {
            iv_my_answer_0.setVisibility(View.VISIBLE);
            iv_my_answer_1.setVisibility(View.VISIBLE);
            iv_my_answer_2.setVisibility(View.VISIBLE);
            Glide.with(this).asBitmap()
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .load(list.get(0)).into(iv_my_answer_0);
            Glide.with(this).asBitmap()
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .load(list.get(1)).into(iv_my_answer_1);
            Glide.with(this).asBitmap()
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .load(list.get(2)).into(iv_my_answer_2);
        }

    }

    /**
     * 显示试题
     */
    private void showFlexibleRichTextView(final FlexibleRichTextView view, String cotent, List<String> opts, String questionNo) {
        view.resetTextView();
        final StringBuilder stringBuilder = new StringBuilder();
        float f_size = getResources().getDimension(R.dimen.dp_15);
        if(questionNo != null) {
            stringBuilder.append(String.format("%s. ",questionNo));
        }

        stringBuilder.append(FormulaUtil.reLatex(cotent));

        if(opts != null && opts.size() > 0) {
            int o_index = 0;
            for(String value : opts) {
                if(value != null && !StringUtil.isEmpty(value) && o_index < OptionStr.OPS.length) {
                    if(o_index > 0) {
                        stringBuilder.append("\r\n");
                    }
                    stringBuilder.append(OptionStr.OPS[o_index] + ". ");
                    stringBuilder.append(FormulaUtil.reLatex(value));
                    o_index++;
                }
            }
        }
        LogUtils.i(stringBuilder.toString());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view.setText(stringBuilder.toString());
            }
        });

    }

    /**
     * 讲解弹框
     */
    private void createTeacherPop() {

        View popView = LayoutInflater.from(this).inflate(R.layout.homework_teacher_pop, null);
        rcy_pop_teacher = popView.findViewById(R.id.rcy_pop_teacher);
        initPopRcyView();
        popWindowTeacher = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(popView)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        iv_popDownUp.setImageResource(R.drawable.common_arrow_down);
                    }
                }).create();
    }

    /**
     * 初始化教材列表数据
     * @param
     */
    private void initPopRcyView() {

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        explainTeacherAdapter = new HomeworkExplainAdapter(this);
        explainTeacherAdapter.setOnItemClickListener(new HomeworkExplainAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                tv_pop_teacher_name.setText(explainListBeans.get(position).getExplain_name());
                if(!isPlayVoiceComment && curExplainBean != null && explainListBeans.get(position).getId().intValue() != curExplainBean.getId()) {
                    playBinder.callStopMusic();
                    resetTime(true, false);
                }
                initExplainView(curExplainBean = explainListBeans.get(position));
                popWindowTeacher.dissmiss();
            }
        });
        rcy_pop_teacher.setLayoutManager(mLayoutManager);
        rcy_pop_teacher.setAdapter(explainTeacherAdapter);
        rcy_pop_teacher.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    private void showExplainPop(){
        popWindowTeacher.showAsDropDown(ll_pop_teacher, ll_pop_teacher.getWidth() / 2 - popWindowTeacher.getWidth() / 2, 14);
        iv_popDownUp.setImageResource(R.drawable.common_arrow_up);
    }

    private void initExplainView(ExplainBean bean){
        if (bean==null)return;
        tv_pop_teacher_name.setText(bean.getExplainName() == null ? bean.getExplain_name() : bean.getExplainName());
        if (bean.getExplainType().intValue() == Constants.TYPE_AUDIO){
            ll_audio.setVisibility(View.VISIBLE);
            ll_video.setVisibility(View.GONE);
            if (bean.getVideoTime()!=null){
                mDuration = bean.getVideoTime() * 1000;
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(bean.getVideoTime() * 1000)));
            }else{
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime( 0)));
            }
        }else if (bean.getExplainType().intValue() == Constants.TYPE_VIDEO){
            ll_audio.setVisibility(View.GONE);
            ll_video.setVisibility(View.VISIBLE);
            tv_video.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_video_mp4,0,0,0);
            if (bean.getVideoTime() != null){
                tv_video.setText(ComUtil.stringForTime(bean.getVideoTime() * 1000));
            }else{
                tv_video.setText(ComUtil.stringForTime(0));
            }

        }else if (bean.getExplainType().intValue() == Constants.TYPE_TRACK){
            ll_audio.setVisibility(View.GONE);
            ll_video.setVisibility(View.VISIBLE);
            tv_video.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_video_track,0,0,0);
            if (bean.getVideoTime()!=null){
                tv_video.setText(ComUtil.stringForTime(bean.getVideoTime() * 1000));
            }else{
                tv_video.setText(ComUtil.stringForTime(0));
            }
        }
    }

    /**
     * 跳转播放视频页面
     */
    private void gotoPlayVideActivity() {
        if (curExplainBean.getExplainType().intValue() == Constants.TYPE_VIDEO){
            ARouter.getInstance().build(ConstantArouter.PATH_LECTURE_LECTUREVIDEOACTIVITY)
                    .withString("videoInfo", JsonUtils.toJson(curExplainBean))
                    .withString("title", curExplainBean.getExplainName() == null ? curExplainBean.getExplain_name() + "" : curExplainBean.getExplainName())
                    .navigation();
        } else if (curExplainBean.getExplainType().intValue() == Constants.TYPE_TRACK) {
            ARouter.getInstance().build(ConstantArouter.PATH_LECTURE_LECTUREPLAYVIDEOEXPLAINACTIVITY)
                    .withString("explainName",curExplainBean.getExplainName())
                    .withString("explainUrl",curExplainBean.getExplainUrl())
                    .withInt("explainType",curExplainBean.getExplainType())
                    .withInt("videoTime",curExplainBean.getVideoTime())
                    .navigation();
        }
    }

    /**
     * 初始化音频播放服务
     */
    private void initPlayService() {
        Intent playService = new Intent(this, PlayService.class);
        this.bindService(playService, playConnection, Service.BIND_AUTO_CREATE);
    }

    /**
     * 初始化音量
     */
    private void initVolume() {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    /**
     * 更新音频时间
     * @param duration
     */
    private void updateCurrentTime(int cur, int duration) {
        String audioTime;
        if (duration < 0 || cur == 0){
            audioTime = String.format("%s/%s", "00:00", ComUtil.strToTime(duration / 1000 + ""));
        }else {
            audioTime = String.format("%s/%s", ComUtil.strToTime(cur / 1000 + ""), ComUtil.strToTime(duration / 1000 + ""));
        }
        if(isPlayVoiceComment) {
            tv_comment_time.setText(audioTime);
        } else {
            tv_audio_time.setText(audioTime);
        }
    }

    private void resetTime(boolean isResetExplain, boolean isResetVoiceComment) {
        if (isResetExplain) {
            if (curExplainBean != null && curExplainBean.getVideoTime() != null) {
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(curExplainBean.getVideoTime() * 1000)));
            } else {
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(0)));
            }
            iv_audio_play_or_pause.setImageResource(R.drawable.common_video_start);
            rsb_audio_progress.setProgress(0);
        }
        if (isResetVoiceComment) {
            if (mExam.getQuestionList().get(mQuestionIndex) != null && mExam.getQuestionList().get(mQuestionIndex).getVoiceCommentDuration() != null) {
                tv_comment_time.setText(String.format("%s/%s", "00:00",
                        ComUtil.stringForTime(mExam.getQuestionList().get(mQuestionIndex).getVoiceCommentDuration() * 1000)));
            } else {
                tv_comment_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(0)));
            }
            iv_comment_play_or_pause.setImageResource(R.drawable.common_video_start);
            rsb_comment_progress.setProgress(0);
        }
    }

    /**
     * 音频拖动监听
     */
    private void listenerRangeChanged() {

        rsb_audio_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFromUser) {
                    rsb_fromUser_value = leftValue;
                    LogUtils.i("rsb_audio_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);

                }
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                int cur = (int) (rsb_fromUser_value / view.getMaxProgress() * mDuration);
                if (playBinder != null &&  playBinder.callPlayStatus() != PlayService.STATUS_MUSIC_IDE_PRE){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateCurrentTime(cur,mDuration);
                        }
                    });

                    playBinder.callSeekTo(cur);
                }
                System.out.println("onStopTrackingTouch:" + "cur ==" + cur + ",mDuration==" + mDuration + "isPlayVoiceComment =" + isPlayVoiceComment);
            }
        });
        rsb_comment_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFromUser) {
                    rsb_fromUser_value = leftValue;
                    LogUtils.i("rsb_audio_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);

                }
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                int cur = (int) (rsb_fromUser_value / view.getMaxProgress() * mDuration);
                if (playBinder != null &&  playBinder.callPlayStatus() != PlayService.STATUS_MUSIC_IDE_PRE){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateCurrentTime(cur,mDuration);
                        }
                    });
                    playBinder.callSeekTo(cur);
                }


            }
        });
    }

    /**
     * 播放音频
     * @param url
     */
    private void setPlayMusicUrl(String url) {
        if (playBinder != null) {
            playBinder.callSetmUrl(url);
        }
    }

    private void audioPlayOrPause() {
        String url = "";
        if(isPlayVoiceComment) {
            url = mExam.getQuestionList().get(mQuestionIndex).getVoiceComment();
        } else {
            url = curExplainBean.getExplainUrl();
        }
        if (playBinder != null) {
            if (audioPath == null || !audioPath.equals(url)){
                if(url != null) {
                    mDuration = 0;
                    setPlayMusicUrl(url);
                } else if(playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                    playBinder.callPauseMusic();
                }
            }  else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                //暂停
                playBinder.callPauseMusic();
            } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
                    || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_IDE
            ) {
                //恢复
                playBinder.callPlayMusic();
            } else if(playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_STOP
                    || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_COMPLETE) {
                if(url != null) {
                    mDuration = 0;
                    setPlayMusicUrl(url);
                }
            }
        }
        audioPath = url;
    }

    private ServiceConnection playConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playBinder = (PlayService.PlayBinder) service;
            playService = playBinder.getService();
            getPresenter().getQuestionList(ComUtil.getHashmapByStr(
                    new String[]{"examPublishId", "studentExamId"},
                    new String[]{publishId + "", studentExamId +""}), true, false);
            playService.setCallback(new PlayService.CallbackPlay() {
                @Override
                public void onDataTestChange(String data) {

                }

                @Override
                public void onMusicStausChange(int status) {
                    iv_comment_play_or_pause.setImageResource(R.drawable.common_video_start);
                    iv_audio_play_or_pause.setImageResource(R.drawable.common_video_start);
                    if(status == PlayService.STATUS_MUSIC_PLAY) {
                        if(isPlayVoiceComment) {
                            iv_comment_play_or_pause.setImageResource(R.drawable.common_video_pause);
                        } else {
                            iv_audio_play_or_pause.setImageResource(R.drawable.common_video_pause);
                        }
                    }
                }

                @Override
                public void onCurrentPosition(int currentPosition, int duration) {
                    runOnUiThread(() -> {
                        if (duration > 0 && currentPosition <= duration) {
                            if(mDuration == 0 && duration != 0) {
                                mDuration = duration;
                                if(isPlayVoiceComment) {
                                    rsb_comment_progress.setRange(0, mDuration);
                                } else {
                                    rsb_audio_progress.setRange(0, mDuration);
                                }
                            } else if(mDuration != 0){
                                if(isPlayVoiceComment) {
                                    rsb_comment_progress.setProgress(currentPosition);
                                } else {
                                    rsb_audio_progress.setProgress(currentPosition);
                                }
                            }
                            updateCurrentTime(currentPosition, duration);
                        }
                    });
                }

                @Override
                public void onCompletion() {

                }

                @Override
                public void OnDuration(int duration) {

                }

                @Override
                public void onLoadedUrl() {

                    if (playBinder != null) {
                        if(isPlayVoiceComment && !isCommentAutoPaly) {
                            isCommentAutoPaly = true;
                        } else {
                            playBinder.callPlayMusic();
                        }

                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
}
